package com.example.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.QueryPageParam;
import com.example.common.Result;
import com.example.exception.ServiceException;
import com.example.pojo.Menu;
import com.example.pojo.User;
import com.example.service.MenuService;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        List<User> userList = userService.lambdaQuery().eq(User::getNo, user.getNo()).list();
        if(userList.size()>0){
            throw new ServiceException("账号已存在");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setName("warehouse"+ RandomUtil.randomInt(10));
        return userService.save(user) ? Result.success() : Result.error();
    }

    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no) {
        List<User> userList = userService.lambdaQuery().eq(User::getNo, no).list();
        return userList.size() > 0 ? Result.success(userList) : Result.error();

    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String password= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        List<User> userList = userService.lambdaQuery()
                .eq(User::getNo, user.getNo())
//                .eq(User::getPassword, user.getPassword())
                .eq(User::getPassword, password)
                .list();

        if(userList.size()>0){
            User user1=userList.get(0);
            List<Menu> menuList = menuService.lambdaQuery().like(Menu::getMenuright, user1.getRoleId()).list();
            HashMap res=new HashMap();
            res.put("user",user1);
            res.put("menu",menuList);

//            下发jwt令牌
            Map<String,Object> claims=new HashMap<>();
            claims.put("no",user1.getNo());
            claims.put("name",user1.getName());
            String jwt = JwtUtils.generateJwt(claims);
            res.put("token",jwt);

            return Result.success(res);
        }
        return Result.error();
    }

    //新增
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        return userService.save(user) ? Result.success() : Result.error();
    }

    @GetMapping("/list")
    public Result list() {
        return Result.success(userService.list());
    }

    //删除
    @DeleteMapping("/del")
    public Result delete(@RequestParam String id) {
        return userService.removeById(id) ? Result.success() : Result.error();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        return userService.updateById(user) ? Result.success() : Result.error();
    }

    //更新密码
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return userService.updateById(user) ? Result.success() : Result.error();
    }


    //修改
    @PutMapping("/mod")
    public boolean mod(@RequestBody User user) {
        return userService.updateById(user);
    }

    //查询（模糊匹配）
    @GetMapping("/listLike")
    public List<User> listLike(@RequestBody User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getName, user.getName());
        return userService.list(lambdaQueryWrapper);
    }

    //新增或修改
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

    //分页
    @PostMapping("/listPage")
    public List<User> listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);

        IPage result = userService.page(page, lambdaQueryWrapper);
        System.out.println("total==" + result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC")
    public List<User> listPageC(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
//        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
//        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.pageC(page);
        System.out.println("total==" + result.getTotal());

        return result.getRecords();
    }

    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        String sex = (String) param.get("sex");
        String roleId = (String) param.get("roleId");
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
            lambdaQueryWrapper.like(User::getName, name);
        }
        if (StringUtils.isNotBlank(sex)) {
            lambdaQueryWrapper.eq(User::getSex, sex);
        }
        if (StringUtils.isNotBlank(roleId)) {
            lambdaQueryWrapper.eq(User::getRoleId, roleId);
        }

        IPage result = userService.pageCC(page, lambdaQueryWrapper);

        System.out.println("total==" + result.getTotal());

        System.out.println(result.getTotal());

        return Result.success(result.getTotal(), result.getRecords());
    }

    @GetMapping("/charts")
    public Result charts(){
        List<Dict> barList = new ArrayList<>();
        List<User> list = userService.list();
        Set<Integer> integerList = list.stream().map(User::getSex).collect(Collectors.toSet());
        for (Integer i:integerList) {
            long count = list.stream().filter(user -> user.getSex() == i).count();
            Dict dict = Dict.create();
            if(i==0){
                Dict bar0 = dict.set("name", "女性").set("value", count);
                barList.add(bar0);
            }
            else if(i==1){
                Dict bar1= dict.set("name","男性").set("value",count);
                barList.add(bar1);
            }
        }
        Dict bar = Dict.create().set("bar", barList);
        return Result.success(bar);
    }


}
